<template>
  <div class="divandpro">
    <!--    <div class="productlog" @click="visitproducts">-->
    <!--      <template v-for="(tag) in tags">-->
    <!--        <a-tag  :key="tag.productCode"  style="margin: 0 3px"  @close="logsdisappear(tag.productCode)" color="#108ee9"  class="tagsmoment">-->
    <!--          {{ tag.productName }}-->
    <!--        </a-tag>-->
    <!--      </template>-->
    <!--    </div>-->
    <!--    <a-button type="primary"   >-->
    <!--    <a-button type="primary" shape="circle" icon="search" @click="visitproducts" class='buttonadd' />-->
    <!--      <span class="addsadd"><a-icon type="plus" /></span>-->
    <!--对话框区域-->
    <j-modal
      :title="name + '选择'"
      width="60%"
      :visible="display"
      switchFullscreen
      @ok="handleOk"
      @cancel="close"
      cancelText="关闭">
      <!--        <div id="movebox"   @click="handleMove(e)"  class="movebox">-->
      <a-row :gutter="18">
        <a-col :span="16">
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchQuery">
              <a-row :gutter="24">
                <!--                <a-col :xl="6" :lg="7" :md="8" :sm="24">-->
                <!--                  <a-cascader :options="treesdata"    change-on-select  @change="changeselect" :fieldNames="fieldNames" placeholder="请选择" expandTrigger="hover" />-->
                <!--                </a-col>-->
                <a-col :xl="15" :lg="15" :md="15" :sm="24">
                  <a-form-item label="订单编号">
                    <a-input placeholder="请输入名称模糊查询" v-model="queryParam.productCode"></a-input>
                  </a-form-item>
                </a-col>
                <!--                <a-col :xl="6" :lg="7" :md="8" :sm="24">-->
                <!--                  <a-form-item label="商品名称">-->
                <!--                    <a-input placeholder="请输入名称模糊查询" v-model="queryParam.productName"></a-input>-->
                <!--                  </a-form-item>-->
                <!--                </a-col>-->
                <div style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-col :xl="6" :lg="7" :md="8" :sm="24">
                    <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                    <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
                  </a-col>
                </div>
              </a-row>
            </a-form>
          </div>
          <a-table
            size="middle"
            bordered
            class='Table'
            rowKey="orderCode"
            :columns="innerColumns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :scroll="{ y: 240 }"
            :rowSelection="{selectedRowKeys, onChange: onSelectChange, type:'radio'}"
            :customRow="customRowFn"
            @change="handleTableChange">
          </a-table>
        </a-col>
        <a-col :span="8">
          <a-card :title="'已选' + name" :bordered="false" :head-style="{padding:0}" :body-style="{padding:0}">
            <a-table size="middle" :rowKey="rowKey" bordered v-bind="selectedTable" :columns="innerColumns">
              <span slot="action" slot-scope="text, record, index">
                <a @click="handleDeleteSelected(record, index)">删除</a>
              </span>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </j-modal>
  </div>
</template>

<script>
import { Cascader } from 'ant-design-vue'
import Ellipsis from '@/components/ellipsis'
import { PageListMixin } from '@/mixins/PageListMixin'
import { cloneObject, pushIfNotExist } from '@/utils/util'
import lodash from 'lodash'
import { getAction, postAction } from '@/api/manage'
import { filterObj } from '@/utils/util'

export default {
  name: 'terminalOrderlist',
  mixins: [PageListMixin],
  components: { Ellipsis, Cascader },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    checkVal: {
      type: Function | Object
    },
    visible: {
      type: Boolean,
      default: false
    },
    // valueKey: {
    //   type: String,
    //   required: true
    // },
    multiple: {
      type: Boolean,
      default: true
    },
    width: {
      type: Number,
      default: 900
    },

    name: {
      type: String,
      default: '关联订单'
    },
    // listUrl: {
    //   type: String,
    //   required: true,
    //   default: ''
    // },
    // 根据 value 获取显示文本的地址，例如存的是 userName，可以通过该地址获取到 realName
    valueUrl: {
      type: String,
      default: ''
    },
    displayKey: {
      type: String,
      default: null
    },
    // columns: {
    //   type: Array,
    //   required: true,
    //   default: () => []
    // },
    // 查询条件Code
    queryParamCode: {
      type: String,
      default: null
    },
    // 查询条件文字
    queryParamText: {
      type: String,
      default: null
    },
    rowKey: {
      type: String,
      default: 'orderCode'
    },
    // 过长裁剪长度，设置为 -1 代表不裁剪
    ellipsisLength: {
      type: Number,
      default: 12
    }
  },
  data() {
    return {
      columns: [],
      valueKey: '',
      display: false,
      innerColumns: [
        {
          title: '订单编号',
          dataIndex: 'orderCode',
          align: 'center',
          scopedSlots: { customRender: 'orderCode' }
        },
        // {
        //   title: '商品名称',
        //   dataIndex: 'productName',
        //   align: 'center',
        //   scopedSlots: { customRender: 'productName' }
        // },
        {
          title: '操作',
          dataIndex: 'action',
          width: 60,
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      manychoice: [],
      treesdata: [],
      fieldNames: {
        value: 'typeCode',
        label: 'typeName',
        children: 'children'
      },
      // tags: [{ productName: '暂无关联商品，您可以为金额券选择关联商品' }],
      innerValue: [],
      // 已选择列表
      selectedTable: {
        pagination: false,
        scroll: { y: 240 },

        dataSource: []
      },
      renderEllipsis: (value) => (<ellipsis length={this.ellipsisLength}>{value}</ellipsis>),
      url: {
        // list: window._CONFIG['domianURL']+"/cnProductController/getProductListByCust",
        treedata: window._CONFIG['domianURL'] + '/goodsclassify/cnGoodsClassify/getProductTypeTree',
        list: window._CONFIG['domianURL'] + '/order/cnOrderReturnItemController/getByOderCode'
      },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      options: [],
      dataSourceMap: {}
    }
  },
  computed: {
    // 表头
  },
  watch: {
    'checkVal': {
      deep: true,
      immediate: true,
      handler(val) {
        this.$nextTick(() => {
          if (val && !lodash.isEmpty(val)) this.$set(this, 'queryParam', val)
        })
      }
    },
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        this.$nextTick(() => {
          this.innerValue = cloneObject(val)
          this.selectedRowKeys = []
          this.valueWatchHandler(val)

          // this.queryOptionsByValue(val)
        })
      }
    },
    dataSource: {
      deep: true,
      handler(val) {
        this.emitOptions(val)
        this.valueWatchHandler(this.innerValue)
      }
    },
      // selectedRowKeys: {
      //   immediate: true,
      //   deep: true,
      //   handler(val) {
      //     this.selectedTable.dataSource = val.map(key => {
      //       for (let data of this.dataSource) {
      //         if (data[this.rowKey] === key) {
      //           pushIfNotExist(this.innerValue, data[this.valueKey])
      //           return data
      //         }
      //       }
      //       for (let data of this.selectedTable.dataSource) {
      //         if (data[this.rowKey] === key) {
      //           pushIfNotExist(this.innerValue, data[this.valueKey])
      //           return data
      //         }
      //       }
      //       console.warn('未找到选择的行信息，key：' + key)
      //       return {}
      //     })
      //   }
      // }
  },

  methods: {
    logsdisappear(code) {
      console.log(code)
    },

    // 级联选择器多选
    changeselect(change) {
      let a = ''
      this.manychoice = []
      if (change.length == 1) {
        a = change[0]
      } else {
        a = change[change.length - 1]
      }
      postAction(this.url.list, { 'typeCode': a }).then(res => {
        if (res.code !== 200) {
          this.$message.error('获取分类信息失败')
          return
        }
        this.dataSource = res.result.records
      })

    },
    // 重置数据
    searchReset() {
      this.queryParam = {}
      this.loadData(1)
    },
    getQueryParams() {
      //高级查询器  数据采集
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      let param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)

      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      delete param.birthdayRange //范围参数不传递后台
      return filterObj(param)
    },
    // 获取树状数据
    visitproducts(cord) {
      // console.log(cord)
      postAction(this.url.list, { 'terminalCode': cord }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message)
        }
        console.log(res)
        this.dataSource = []
        this.dataSource.push(...res.result.records)
      })
      this.display = true
    },
    /** 关闭弹窗 */
    close() {
      this.selectedTable.dataSource = []
      this.dataSource=[]
      this.display = false
    },

    valueWatchHandler(val) {
      console.log(this.valueKey)
      val.forEach(item => {
        this.dataSource.concat(this.selectedTable.dataSource).forEach(data => {
          if (data[this.valueKey] === item) {
            pushIfNotExist(this.selectedRowKeys, data[this.rowKey])
          }
        })
      })
    },

    getParams() {
      const params = this.checkVal || {}
      for (let key of Object.keys(params)) {
        if (key && (params[key] === undefined || params[key] === '')) {
          return false
        }
      }
      return this.lodash.isEmpty(params) ? true : params
    },

    queryOptionsByValue(value) {
      console.log(this)
      const params = this.getParams()
      if (!params) return
      if (typeof params === 'boolean' && params) {
        if (!value || value.length === 0) {
          return
        }
        // 判断options是否存在value，如果已存在数据就不再请求后台了
        let notExist = false
        for (let val of value) {
          let find = false
          for (let option of this.options) {
            if (val === option.value) {
              find = true
              break
            }
          }
          if (!find) {
            notExist = true
            break
          }
        }
        if (!notExist) return
      }
      postAction(this.url.list, {
        // 这里最后加一个 , 的原因是因为无论如何都要使用 in 查询，防止后台进行了模糊匹配，导致查询结果不准确
        // [this.valueKey]: value.join(',') + ',',
        pageNo: 1,
        pageSize: value.length,
        ...params
      }).then((res) => {
        if (res.success) {
          let dataSource = res.result
          if (!(dataSource instanceof Array)) {
            dataSource = res.result.records
          }
          this.emitOptions(dataSource, (data) => {
            pushIfNotExist(this.innerValue, data[this.valueKey])
            pushIfNotExist(this.selectedRowKeys, data[this.rowKey])
            pushIfNotExist(this.selectedTable.dataSource, data, this.rowKey)
          })
        }
      })
    },
    emitOptions(dataSource, callback) {
      dataSource.forEach(data => {
        let key = data[this.valueKey]
        this.dataSourceMap[key] = data
        pushIfNotExist(this.options, { label: data[this.displayKey], value: key }, 'value')
        typeof callback === 'function' ? callback(data) : ''
      })
      this.$emit('options', this.options, this.dataSourceMap)
    },
// 鼠标移动事件

    /** 完成选择 */
    handleOk() {
      let value = this.selectedTable.dataSource.map(item => item.orderCode)
      console.log(value)
      // let value = this.selectedRowKeys
      // this.$emit('productcon', value)
      this.$emit('productcon', value)
      // this.$emit('update:display', false)

      this.close()
    },

    /** 删除已选择的 */
    handleDeleteSelected(record, index) {
      this.selectedRowKeys.splice(this.selectedRowKeys.indexOf(record[this.rowKey]), 1)
      this.selectedTable.dataSource.splice(index, 1)
    },
    customRowFn(record) {
      return {
        on: {
          click: () => {
            let key = record[this.rowKey]
            if (!this.multiple) {
              this.selectedRowKeys = [key]
              this.selectedTable.dataSource = [record]
            } else {
              let index = this.selectedRowKeys.indexOf(key)
              if (index === -1) {
                this.selectedRowKeys = [key]
                this.selectedTable.dataSource = [record]
              } else {
                this.handleDeleteSelected(record, index)
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
.divandpro {
  display: flex;
  flex-direction: row;


  .buttonadd {
    margin: 2px 0 0 15px;
    box-shadow: 0 0 3px 3px rgb(205, 205, 205);
    height: 40px;
    width: 40px;
  }

  .buttonadd:hover {
    box-shadow: 0 0 5px 5px rgb(205, 205, 205);
  }

  .addsadd {
    transform: translateX(-4px);
  }
}

.productlog {
  width: 90%;
  color: red;
  border: 1px solid rgb(205, 205, 205);
  padding: 2px 0 2px 4px;
  border-radius: 5px;
  box-sizing: border-box;
}

.productlog:hover {
  border: 1px solid rgb(2, 14, 225);

}

.tagsmoment {
  font-size: 12px;
  letter-spacing: 0.1em;
}
</style>